package wymiana.mbeans.mail;

import java.util.Date;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import wymiana.domain.Mail;
import wymiana.domain.User;
import wymiana.mbeans.UserBean;
import wymiana.service.MailService;
import wymiana.service.UserService;

@ManagedBean(name = "mailMBean")
@SessionScoped
public class MailMBean {
	@ManagedProperty("#{mailService}")
	private MailService mailService;

	@ManagedProperty("#{userService}")
	private UserService userService;

	@ManagedProperty("#{userMBean}")
	private UserBean userMBean;

	private List<Mail> allMails;

	private List<Mail> allSend;

	private Mail actualMail;

	private List<Mail> allTrash;

	private String recipientName = null;

	public String showAllReceived() {
		final User user = userMBean.getLoggedUser();
		allMails = ((MailService) mailService)
				.getMailsByRecipient(user);

		return "allMails";
	}

	public String getMailCount() {
		final User user = userMBean.getLoggedUser();
		int count = 0;
		try {
			count = ((MailService) mailService).getNewMailsCount(user);
		} catch (Exception e) {

		}

		String result = "0";
		if (count > 0)
			result = "" + count;

		return result;
	}

	/** wysłane */
	public String showAllSend() {
		final User user = userMBean.getLoggedUser();

		allSend = ((MailService) mailService).getMailsBySender(user);
		return "allSend";
	}

	public String showMail() {

		ExternalContext externalContext = FacesContext.getCurrentInstance()
				.getExternalContext();

		String id = (String) externalContext.getRequestParameterMap().get(
				"mailId");
		final User user = userMBean.getLoggedUser();

		Mail mail = mailService.getMailByUserAndId(user, Long.parseLong(id));
		if (mail == null) {
			FacesMessage message = new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "Błąd: ",
					"Brak takiego maila.");
			FacesContext.getCurrentInstance().addMessage(null, message);
			return "";
		}
		if (user.equals(mail.getRecipient())) {
			mail.setReaded(true);
			mailService.updateMail(mail);
		}
		actualMail = mail;
		return "showMail";
	}

	public String newMail() {
		actualMail = new Mail();

		return "newMail";
	}

	public String showTrash() {
		final User user = userMBean.getLoggedUser();

		allTrash = ((MailService) mailService)
				.getMailsByUserTrash(user);
		return "allTrash";
	}

	public String saveMail() {
		User sender = userMBean.getLoggedUser();

		User recipient = (User) userService
				.getUserByUsername(recipientName);

		if (recipient == null) {
			FacesMessage message = new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "Błąd: ",
					"Brak użytkownika o takiej nazwie.");
			FacesContext.getCurrentInstance().addMessage(null, message);
			return "";
		}

		actualMail.setDate(new Date());
		actualMail.setRecipient(recipient);
		actualMail.setSender(sender);
		actualMail.setDeleted(false);
		actualMail.setDeleted_sender(false);
		actualMail.setReaded(false);
		actualMail.setTrash(false);
		actualMail.setTrash_sender(false);
		mailService.sendMail(actualMail);
		return showAllSend();
	}

	public String deleteMailFromInbox() {
		final User recipient = userMBean.getLoggedUser();
		ExternalContext externalContext = FacesContext.getCurrentInstance()
				.getExternalContext();

		String id = (String) externalContext.getRequestParameterMap().get(
				"mailId");
		Mail mail = mailService.getMailByUserAndId(recipient,
				Long.parseLong(id));
		if (mail == null) {
			FacesMessage message = new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "Błąd: ", "Brak takiego maila");
			FacesContext.getCurrentInstance().addMessage(null, message);
			return "";

		} else {
			mail.setTrash(true);
			if (mail.getDate() == null)
				mail.setDate(new Date());
			mailService.updateMail(mail);
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN,
					"Uwaga: ", "Mail przeniesiony do kosza.");
			FacesContext.getCurrentInstance().addMessage(null, message);
		}

		return showAllReceived();
	}

	public String deleteMailFromOutbox() {
		final User recipient = userMBean.getLoggedUser();
		ExternalContext externalContext = FacesContext.getCurrentInstance()
				.getExternalContext();

		String id = (String) externalContext.getRequestParameterMap().get(
				"mailId");
		Mail mail = mailService.getMailByUserAndId(recipient,
				Long.parseLong(id));
		if (mail == null) {
			FacesMessage message = new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "Błąd: ", "Brak takiego maila");
			FacesContext.getCurrentInstance().addMessage(null, message);

		} else {
			mail.setTrash_sender(true);

			mailService.updateMail(mail);
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN,
					"Uwaga: ", "Mail przeniesiony do kosza");
			FacesContext.getCurrentInstance().addMessage(null, message);
		}

		return showAllSend();
	}

	public String deleteMailPermanently() {
		final User user = userMBean.getLoggedUser();
		ExternalContext externalContext = FacesContext.getCurrentInstance()
				.getExternalContext();

		String id = (String) externalContext.getRequestParameterMap().get(
				"mailId");
		final Mail mail = (Mail) mailService.getMailById(Long.parseLong(id));
		if (mail == null) {
			FacesMessage message = new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "Błąd: ", "Brak takiego maila");
			FacesContext.getCurrentInstance().addMessage(null, message);
			return "";
		}

		if (mail.getSender().equals(user)
				&& mail.getRecipient().equals(user)
				&& (mail.getTrash_sender() == Boolean.TRUE || mail.getTrash() == Boolean.TRUE)) {
			mail.setDeleted_sender(true);
			mail.setDeleted(true);
			mailService.updateMail(mail);
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN,
					"Uwaga: ", "Mail zoastał usuniety");
			FacesContext.getCurrentInstance().addMessage(null, message);
		} else if (mail.getSender().equals(user)
				&& mail.getTrash_sender() == Boolean.TRUE) {
			// deleted_sender
			mail.setDeleted_sender(true);
			mailService.updateMail(mail);
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN,
					"Uwaga: ", "Mail zoastał usuniety");
			FacesContext.getCurrentInstance().addMessage(null, message);
		} else if (mail.getRecipient().equals(user)
				&& mail.getTrash() == Boolean.TRUE) {
			// deleted
			mail.setDeleted(true);
			mailService.updateMail(mail);
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN,
					"Uwaga: ", "Mail zoastał usuniety");
			FacesContext.getCurrentInstance().addMessage(null, message);
		} else {
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN,
					"Uwaga: ", "Nie posiadasz takiego maila w koszu.");
			FacesContext.getCurrentInstance().addMessage(null, message);
		}

		return showTrash();
	}

	/**
	 * @return the mailService
	 */
	public MailService getMailService() {
		return mailService;
	}

	/**
	 * @param mailService
	 *            the mailService to set
	 */
	public void setMailService(MailService mailService) {
		this.mailService = mailService;
	}

	/**
	 * @return the userService
	 */
	public UserService getUserService() {
		return userService;
	}

	/**
	 * @param userService
	 *            the userService to set
	 */
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	/**
	 * @return the userMBean
	 */
	public UserBean getUserMBean() {
		return userMBean;
	}

	/**
	 * @param userMBean
	 *            the userMBean to set
	 */
	public void setUserMBean(UserBean userMBean) {
		this.userMBean = userMBean;
	}

	/**
	 * @return the allMails
	 */
	public List<Mail> getAllMails() {
		return allMails;
	}

	/**
	 * @param allMails
	 *            the allMails to set
	 */
	public void setAllMails(List<Mail> allMails) {
		this.allMails = allMails;
	}

	/**
	 * @return the allSend
	 */
	public List<Mail> getAllSend() {
		return allSend;
	}

	/**
	 * @param allSend
	 *            the allSend to set
	 */
	public void setAllSend(List<Mail> allSend) {
		this.allSend = allSend;
	}

	/**
	 * @return the actualMail
	 */
	public Mail getActualMail() {
		return actualMail;
	}

	/**
	 * @param actualMail
	 *            the actualMail to set
	 */
	public void setActualMail(Mail actualMail) {
		this.actualMail = actualMail;
	}

	/**
	 * @return the allTrash
	 */
	public List<Mail> getAllTrash() {
		return allTrash;
	}

	/**
	 * @param allTrash
	 *            the allTrash to set
	 */
	public void setAllTrash(List<Mail> allTrash) {
		this.allTrash = allTrash;
	}

	/**
	 * @return the recipientName
	 */
	public String getRecipientName() {
		return recipientName;
	}

	/**
	 * @param recipientName
	 *            the recipientName to set
	 */
	public void setRecipientName(String recipientName) {
		this.recipientName = recipientName;
	}
}
